package com.cwits.wifi.ui.dialog;

import android.app.DialogFragment;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.cwits.wifi.MainApplication;
import com.cwits.wifi.R;
import com.cwits.wifi.base.BaseDialogFragment;
import com.cwits.wifi.manager.ControlManager;
import com.cwits.wifi.ui.service.CommunicationService;
import com.cwits.wifi.util.Dbug;
import com.cwits.wifi.util.IConstant;
import com.cwits.wifi.util.PreferencesHelper;
import com.jieli.lib.stream.util.ICommon;

public class ModifyDeviceDialog extends BaseDialogFragment implements IConstant, TextWatcher, ICommon {

    public interface OnChangeListener {
        void ChangePwd(boolean is_pwd);

        void ChangeSsid(boolean is_ssid);
    }

    private OnChangeListener mOnEndListener;
    private final String tag = getClass().getSimpleName();
    private EditText mContent;
    private EditText mFirstContent;
    private TextView mConfirm;
    private TextView mCancel;
    private TextView mError, mPwdError;
    private TextView mInputTips;
    /**
     * SSID范围:1-32个字符, 密码范围:8-63个字符,必须有设置密码
     */
    private final int MAX_WIFI_PWD_LENGTH = 15;
    private final int MIN_WIFI_PWD_LENGTH = 8;
    private final int MAX_WIFI_NAME_LENGTH = 24;
    private final int MAX_INPUT_NAME_LENGTH = MAX_WIFI_NAME_LENGTH - WIFI_PREFIX_CAMERA.length();
    private int mInputLength;
    private String mVariable;
    private String mOldName;
    private String mOldPassword;
    private NotifyDialog mNotifyDialog;

    private final String FILTER_ASCII = "\\A\\p{ASCII}*\\z";

    public static ModifyDeviceDialog newInstance() {
        return new ModifyDeviceDialog();
    }

    public void setOnEndListener(OnChangeListener ls) {
        mOnEndListener = ls;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.modify_device_dialog, container, false);
        mContent = (EditText) v.findViewById(R.id.et_content);
        mFirstContent = (EditText) v.findViewById(R.id.et_first_input);
        mConfirm = (TextView) v.findViewById(R.id.tv_confirm);
        mError = (TextView) v.findViewById(R.id.et_input_error);
        mPwdError = (TextView) v.findViewById(R.id.et_pw_input_error);

        mCancel = (TextView) v.findViewById(R.id.tv_cancel);
        TextView prefixName = (TextView) v.findViewById(R.id.prefix_name);
        mInputTips = (TextView) v.findViewById(R.id.et_input_count);
        //mConfirm.setOnClickListener(mOnClickListener);
        mCancel.setOnClickListener(mOnClickListener);
        mContent.addTextChangedListener(this);
        mConfirm.setOnClickListener(mOnClickListener);
        SharedPreferences sharedPreferences = PreferencesHelper.getSharedPreferences(MainApplication.getApplication());
        mOldName = sharedPreferences.getString(CURRENT_SSID, null);
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (!(source + "").matches(FILTER_ASCII)) {
                    return "";
                }
                return null;
            }
        };
        mContent.setFilters(new InputFilter[]{filter});
        mFirstContent.addTextChangedListener(mFirstInputTextWatcher);
        if (mOldName.startsWith(WIFI_PREFIX_CAMERA)) {
            prefixName.setText(WIFI_PREFIX_CAMERA);
            mVariable = mOldName.substring(WIFI_PREFIX_CAMERA.length());
        } else if(mOldName.startsWith(WIFI_PREFIX_CARDVR)){
            prefixName.setText(WIFI_PREFIX_CARDVR);
            mVariable = mOldName.substring(WIFI_PREFIX_CARDVR.length());
        }else{
            String prename = "";
            int id_index1 = mOldName.indexOf("_");
            int id_index2 = mOldName.indexOf("-");
            if(id_index1 < 0){
                prename = mOldName.substring(0,id_index2 + 1);
                mVariable = mOldName.substring(id_index2 + 1,mOldName.length());
            }else{
                if(id_index2 < 0){
                    prename = mOldName.substring(0,id_index1 + 1);
                    mVariable = mOldName.substring(id_index1 + 1,mOldName.length());
                }else{
                    if(id_index1 > id_index2){
                        prename = mOldName.substring(0,id_index2 + 1);
                        mVariable = mOldName.substring(id_index2 + 1,mOldName.length());
                    }else{
                        prename = mOldName.substring(0,id_index1 + 1);
                        mVariable = mOldName.substring(id_index1 + 1,mOldName.length());
                    }
                }
            }
            prefixName.setText(prename);
        }
        mContent.setText(mVariable);
        mContent.setSelection(0, mContent.getText().length());
        mContent.requestFocus();
        mOldPassword = sharedPreferences.getString(CURRENT_PWD, null);

        if (!TextUtils.isEmpty(mOldPassword)) {
            mFirstContent.setText(mOldPassword);
            mFirstContent.setSelection(0, mFirstContent.getText().length());
            mFirstContent.requestFocus();
        }
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        final WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();

        params.width = 100;
        params.height = 50;
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            params.width = displayMetrics.heightPixels - 20;
            params.height = displayMetrics.heightPixels * 3 / 5;
        } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            params.width = displayMetrics.widthPixels - 20;
            params.height = displayMetrics.widthPixels * 3 / 5;
        }
        params.gravity = Gravity.CENTER;
        getDialog().getWindow().setAttributes(params);
    }

    private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mConfirm == v) {
                final String ssid = mContent.getText().toString().trim();
                final String pwd = mFirstContent.getText().toString().trim();
                if (TextUtils.isEmpty(ssid) || ssid.length() == 0) {
                    showToastLong(R.string.name_empty_error);
                    mError.setVisibility(View.VISIBLE);
                    return;
                }

                if (mInputLength > MAX_INPUT_NAME_LENGTH) {
                    showToastLong(R.string.limited_input);
                    mError.setVisibility(View.VISIBLE);
                    return;
                }
                mError.setVisibility(View.GONE);
                /** ---------------------------------------------------------- */

//

                if (pwd.length() < MIN_WIFI_PWD_LENGTH || pwd.length() > MAX_WIFI_PWD_LENGTH) {
                    showToastLong(R.string.input_pwd_error);
                    mPwdError.setVisibility(View.VISIBLE);
                    mPwdError.setText(getText(R.string.input_pwd_error));
                    return;
                }
                mPwdError.setVisibility(View.GONE);
                commitPassword(pwd);


                /** ---------------------------------------------------------- */
                commitModifyName(ssid+"");
                dismiss();
            } else if (mCancel == v) {
                dismiss();
            }
        }
    };

    private void commitModifyName(final String changedName) {
        if (mVariable.equals(changedName)) {
            Dbug.w(tag, "No change!");
            return;
        }
        if (mOnEndListener != null)
            mOnEndListener.ChangeSsid(true);
        /**Remove current Wi-Fi & the old SSID*/
        SharedPreferences sharedPreferences = PreferencesHelper.getSharedPreferences(MainApplication.getApplication());
        SharedPreferences.Editor editor = sharedPreferences.edit();
        String currentSSID = sharedPreferences.getString(CURRENT_SSID, null);
        editor.remove(CURRENT_PWD);
        editor.remove(CURRENT_SSID);
        editor.remove(mOldName);
        editor.remove(currentSSID);
        if(currentSSID != null)
            editor.putString(currentSSID,null);
        //editor.putString(CURRENT_SSID,WIFI_PREFIX + changedName);
        editor.apply();
        /**Send modified SSID to device*/
        MainApplication.getApplication().setModifySSID(true);
        String recordState = CommunicationService.getInstance().getDeviceStatus(CMD_GET_RECORDING_STATUS);
        Dbug.d(tag, "recordState:" + recordState);
        if (ARGS_IN_RECORDING.equals(recordState)) {
            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_STOP_RECORD, ARGS_STOP_RECORD);
        }
        String pre_name = "";
        if (mOldName.startsWith(WIFI_PREFIX_CAMERA)) {
            pre_name = WIFI_PREFIX_CAMERA;
        } else if(mOldName.startsWith(WIFI_PREFIX_CARDVR)){
            pre_name = WIFI_PREFIX_CARDVR;
        }else {
            int id_index1 = mOldName.indexOf("_");
            int id_index2 = mOldName.indexOf("-");
            if(id_index1 < 0){
                pre_name = mOldName.substring(0,id_index2 + 1);
            }else{
                if(id_index2 < 0){
                    pre_name = mOldName.substring(0,id_index1 + 1);
                }else{
                    if(id_index1 > id_index2){
                        pre_name = mOldName.substring(0,id_index2 + 1);
                    }else{
                        pre_name = mOldName.substring(0,id_index1 + 1);
                    }
                }
            }
        }
        ControlManager.getInstance().sendCommand(ICommon.CTP_ID_DEFAULT, ICommon.CMD_AP_SSID, pre_name + changedName);

    }

    private void commitPassword(final String password) {
        Dbug.d(tag, "commitModifyPassword:[" + password + "]");
        if (mOldPassword.equals(password)) {
            Dbug.w(tag, "Password No Change!");
            return;
        }
        if (mOnEndListener != null)
            mOnEndListener.ChangePwd(true);
        /**Remove current Wi-Fi & the old SSID*/
        SharedPreferences sharedPreferences = PreferencesHelper.getSharedPreferences(MainApplication.getApplication());
        SharedPreferences.Editor editor = sharedPreferences.edit();
        String currentSSID = sharedPreferences.getString(CURRENT_SSID, null);
        editor.remove(CURRENT_PWD);
        //editor.putString(currentSSID,password);
        editor.remove(CURRENT_SSID);
        editor.remove(currentSSID);
        if(currentSSID != null)
            editor.putString(currentSSID,null);
        editor.apply();
        /**Send to device*/
        MainApplication.getApplication().setModifyPWD(true);
        String recordState = CommunicationService.getInstance().getDeviceStatus(CMD_GET_RECORDING_STATUS);
        Dbug.d(tag, "recordState:" + recordState);
        if (ARGS_IN_RECORDING.equals(recordState)) {
            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_STOP_RECORD, ARGS_STOP_RECORD);
        }
        if (password.isEmpty()) {
            Dbug.i(tag, "ARGS_AP_PWD_NONE.:");
            ControlManager.getInstance().sendCommand(ICommon.CTP_ID_DEFAULT, ICommon.CMD_AP_PASSWORD, ICommon.ARGS_AP_PWD_NONE);
        } else {
            Dbug.i(tag, "not ARGS_AP_PWD_NONE:");
            ControlManager.getInstance().sendCommand(ICommon.CTP_ID_DEFAULT, ICommon.CMD_AP_PASSWORD, password);
        }

    }

    private final TextWatcher mFirstInputTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            int mInputLength = mFirstContent.getText().toString().trim().getBytes().length;
            if (mInputLength > MAX_WIFI_PWD_LENGTH) {
                showToastShort(R.string.limited_input);
            }
        }
    };

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        mInputLength = mContent.getText().toString().trim().getBytes().length;
        if (mInputLength > MAX_INPUT_NAME_LENGTH) {
            showToastShort(R.string.limited_input);
        }
    }
}
